package cn.com.myspring.demo.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.myspring.demo.service.IDemoService;
import cn.com.myspring.framework.annotation.MYAutowired;
import cn.com.myspring.framework.annotation.MYController;
import cn.com.myspring.framework.annotation.MYRequestMapping;
import cn.com.myspring.framework.annotation.MYRequestParam;
import cn.com.myspring.framework.webmvc.servlet.MYModelAndView;

@MYController
@MYRequestMapping("/demo")
public class DemoController {

    @MYAutowired
    private IDemoService demoService;

    @MYRequestMapping("/show")
    public MYModelAndView show(HttpServletRequest req, HttpServletResponse resp, @MYRequestParam("title") String title,
            @MYRequestParam("name") String name) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("title", title);
        map.put("name", name);
        map.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String token = "" + (int) ((Math.random() + 1) * 100000);
        map.put("token", token);
        return new MYModelAndView("first", map);
    }

    @MYRequestMapping("/exception")
    public void exception(HttpServletRequest req, HttpServletResponse resp, @MYRequestParam("title") String title,
            @MYRequestParam("name") String name) throws Exception {
        throw new Exception("抛异常啦!!!!");
    }

    @MYRequestMapping("/query")
    public void query(HttpServletRequest req, HttpServletResponse resp, @MYRequestParam("name") String name) {
        try {
            String result = demoService.get(name);
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @MYRequestMapping("/add")
    public void add(HttpServletRequest req, HttpServletResponse resp, @MYRequestParam("a") Integer a,
            @MYRequestParam("b") Integer b) {
        try {
            resp.getWriter().write(a + "+" + b + "=" + (a + b));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @MYRequestMapping("/sub")
    public void add(HttpServletRequest req, HttpServletResponse resp, @MYRequestParam("a") Double a,
            @MYRequestParam("b") Double b) {
        try {
            resp.getWriter().write(a + "-" + b + "=" + (a - b));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @MYRequestMapping("/remove")
    public String remove(@MYRequestParam("id") Integer id) {
        return "" + id;
    }

}
